package network.impl;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.LinkedList;
import java.util.List;

import sharedNetwork.NetworkFlags;

class ClientInputThread extends Thread {
	private ObjectInputStream reader;
	private List<ClientNetworkListener> networkListeners;
	private List<ClientInputThreadListener> inputThreadListeners;
	
	private enum Message {
		CONNECTION_TO_SERVER_LOST, DISCONNECT, DISCONNECTION_ACCEPTED
	}
	
	public ClientInputThread(ObjectInputStream inputReader) {
		reader = inputReader;
		networkListeners = new LinkedList<ClientNetworkListener>();
		inputThreadListeners = new LinkedList<ClientInputThreadListener>();
	}
	
	public void addNetworkListener(ClientNetworkListener listener) {
		networkListeners.add(listener);
	}
	
	public void addInputThreadListener(ClientInputThreadListener listener) {
		inputThreadListeners.add(listener);
	}
	
	@Override
	public void run() {
		Object inputObject = null;
		boolean running = true;
		try {
			while (running && (inputObject = reader.readObject()) != null) {
				if (inputObject.equals(NetworkFlags.DISCONNECT)) {
					notifyInputThreadListeners(Message.DISCONNECT);
					notifyNetworkListeners(Message.DISCONNECT);
					running = false;
				} else if (inputObject.equals(NetworkFlags.DISCONNECTION_ACCEPTED)) {
					notifyInputThreadListeners(Message.DISCONNECTION_ACCEPTED);
					notifyNetworkListeners(Message.DISCONNECTION_ACCEPTED);
					running = false;
				} else {
					sendToNetworkListeners(inputObject);
				}
				sendToNetworkListeners(inputObject);
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO: Replace println with code.
			System.out.println("Preventing the client from crashing");
		}
	}
	
	private void notifyNetworkListeners(Message message) {
		// TODO Auto-generated method stub
		
	}

	private void notifyInputThreadListeners(Message message) {
		if (message.equals(Message.CONNECTION_TO_SERVER_LOST)) {
			for (ClientInputThreadListener listener : inputThreadListeners) {
				listener.connectionLost();
			}
		} else if (message.equals(Message.DISCONNECT)) {
			for (ClientInputThreadListener listener : inputThreadListeners) {
				listener.disconnect();
			}
		} else if (message.equals(Message.DISCONNECTION_ACCEPTED)) {
			for (ClientInputThreadListener listener : inputThreadListeners) {
				listener.disconnectionAccepted();
			}
		}
	}

	private void sendToNetworkListeners(Object obj) {
		for (ClientNetworkListener listener : networkListeners) {
			listener.networkMessageRecieved(obj);
		}
	}
}
